package com.example.commom.es;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RestHighLevelClient;


public class ElasticsearchDeleteCommand extends HystrixCommand<Boolean> {

    private final RestHighLevelClient client;
    private final DeleteRequest request;
    private final ElasticsearchOperation operation;

    public ElasticsearchDeleteCommand(RestHighLevelClient client, DeleteRequest request) {

        // 设置HystrixCommand的分组名为"ElasticsearchGroup"
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ElasticsearchGroup"))
                .andCommandPropertiesDefaults(
                        HystrixCommandProperties.Setter()
                                // 设置超时时间为5秒
                                .withExecutionTimeoutInMilliseconds(5000)
                                // 启用断路器
                                // 断路器是一种用于保护系统的机制，当失败的请求达到一定阈值时,
                                // 断路器将会打开，阻断对该服务的请求，并启用回退逻辑。
                                .withCircuitBreakerEnabled(true)
                                // 错误百分比阈值，当达到该阈值时断路器打开
                                .withCircuitBreakerErrorThresholdPercentage(50)
                                // 最小请求数阈值，当请求数量低于该阈值时断路器不进行熔断
                                .withCircuitBreakerRequestVolumeThreshold(20)
                                // 断路器打开后的休眠时间，在该时间内断路器会通过一个新请求试探是否恢复
                                .withCircuitBreakerSleepWindowInMilliseconds(5000)
                )
        );

        this.client = client;
        this.request = request;
        this.operation = new documentOperation();
    }

    @Override
    protected Boolean run() {
        // 返回操作结果
        return operation.executeDelete(client, request);
    }

    @Override
    protected Boolean getFallback() {
        // 定义失败回退逻辑
        return false;
    }

}